<template>
  <div class="inventory-container">
    <div class="header-actions">
      <div class="search-container">
        <div class="search-input-group">
          <el-select v-model="searchParams.brand" placeholder="全部品牌" class="search-input">
            <el-option label="全部品牌" value="" />
            <el-option v-for="brand in brandList" :key="brand" :label="brand" :value="brand" />
          </el-select>
          <el-select v-model="searchParams.specification" placeholder="全部型号" class="search-input">
            <el-option label="全部型号" value="" />
            <el-option v-for="spec in specificationList" :key="spec" :label="spec" :value="spec" />
          </el-select>
          <el-input
            v-model="searchParams.name"
            placeholder="请输入材料名称"
            class="search-input"
            @keyup.enter="handleSearch"
          />
        </div>
        <el-button type="primary" class="search-button" @click="handleSearch">
          <el-icon><Search /></el-icon>
          查询
        </el-button>
      </div>
    </div>

    <el-table
      v-loading="loading"
      :data="inventorySummaryList"
      style="width: 100%"
    >
      <el-table-column type="index" label="序号" width="100" align="center" />
      <el-table-column prop="name" label="材料名称" width="280" align="left" />
      <el-table-column prop="brand" label="品牌" width="180" align="left" />
      <el-table-column prop="specification" label="规格型号" width="240" align="left" />
      <el-table-column prop="price" label="单位成本" width="160" align="right" />
      <el-table-column prop="stocks" label="当前库存" width="160" align="right" />
      <el-table-column label="操作" width="200">
        <template #default="scope">
            <el-button link type="primary" size="small" @click="handleEdit(scope.row)" style="margin-right: 8px">修改</el-button>
            <el-button link type="danger" size="small" @click="handleDelete(scope.row.id)">删除</el-button>
          </template>
      </el-table-column>
    </el-table>

    <div class="pagination-container">
      <el-pagination
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pagination.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 编辑对话框 -->
    <el-dialog v-model="formDialogVisible" title="编辑库存" width="500px">
      <el-form ref="formRef" :model="formData" label-width="100px">
        <el-form-item label="材料名称" prop="name" :rules="[{ required: true, message: '材料名称不能为空' }]">
          <el-input v-model="formData.name" placeholder="请输入材料名称" disabled />
        </el-form-item>
        <el-form-item label="品牌" prop="brand" :rules="[{ required: true, message: '品牌不能为空' }]">
          <el-input v-model="formData.brand" placeholder="请输入品牌" disabled />
        </el-form-item>
        <el-form-item label="规格型号" prop="specification" :rules="[{ required: true, message: '规格型号不能为空' }]">
          <el-input v-model="formData.specification" placeholder="请输入规格型号" disabled />
        </el-form-item>
        <el-form-item label="单位成本" prop="price" :rules="[{ required: true, message: '单位成本不能为空' }, { type: 'number', min: 0, message: '单位成本必须大于等于0' }]">
          <el-input v-model.number="formData.price" placeholder="请输入单位成本" type="number" />
        </el-form-item>
        <el-form-item label="当前库存" prop="stocks" :rules="[{ required: true, message: '当前库存不能为空' }, { type: 'number', min: 0, message: '当前库存必须大于等于0' }]">
          <el-input v-model.number="formData.stocks" placeholder="请输入当前库存" type="number" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="formDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSave">保存</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 确认对话框 -->
    <el-dialog v-model="confirmDialogVisible" title="确认删除" width="30%">
      <span>确定要删除选中的库存记录吗？</span>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="confirmDialogVisible = false">取消</el-button>
          <el-button type="danger" @click="confirmDelete">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { Search } from '@element-plus/icons-vue';
import { getMaterialList, getMaterialById } from '@/api/material';
import {
  getInventorySummaryList,
  getInventorySummaryById,
  updateInventorySummary,
  deleteInventorySummary
} from '@/api/inventorySummary';
import type { InventorySummaryItem, InventorySummaryListParams, InventorySummaryUpdatePayload } from '@/api/inventorySummary';
import type { MaterialItem } from '@/api/material';

// 状态管理
const loading = ref(false);
const inventorySummaryList = ref<InventorySummaryItem[]>([]);
const searchParams = reactive<InventorySummaryListParams>({
  page: 1,
  limit: 10,
  brand: '',
  specification: '',
  name: ''
});
const brandList = ref<string[]>([]);
const specificationList = ref<string[]>([]);

// 分页数据
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
});

// 对话框状态
const formDialogVisible = ref(false);
const confirmDialogVisible = ref(false);
const currentDeleteId = ref<number | null>(null);
const formRef = ref<any>(null);

// 表单数据
const formData = reactive<InventorySummaryUpdatePayload & { name?: string }>({
  id: 0,
  materialId: 0,
  price: 0,
  stocks: 0,
  updateTime: '',
  createTime: '',
  tenantId: 0,
  name: ''
});

// 获取库存列表
const fetchInventorySummaryList = async () => {
  try {
    loading.value = true;
    const params: InventorySummaryListParams = {
      page: pagination.currentPage,
      limit: pagination.pageSize,
      brand: searchParams.brand,
      specification: searchParams.specification,
      name: searchParams.name
    };
    const response = await getInventorySummaryList(params);
    
    if ((response.code === 0 || response.code === 200) && response.data) {
      const data = response.data;
      
      if (data.data && data.data.records) {
        inventorySummaryList.value = data.data.records;
        pagination.total = data.data.totalRow || 0;
      } else if (data.records) {
        inventorySummaryList.value = data.records;
        pagination.total = data.totalRow || 0;
      } else if (data.list) {
        inventorySummaryList.value = data.list;
        pagination.total = data.total || 0;
      } else {
        inventorySummaryList.value = Array.isArray(data) ? data : [];
        pagination.total = 0;
      }
      
      // 更新品牌和规格型号列表
      updateFilterOptions();
    }
  } catch (error) {
    console.error('获取库存列表失败:', error);
    ElMessage.error('获取数据失败');
  } finally {
    loading.value = false;
  }
};

// 更新筛选选项
const updateFilterOptions = () => {
  // 提取所有品牌
  const brands = Array.from(new Set(inventorySummaryList.value.map(item => item.brand || '').filter(Boolean)));
  brandList.value = brands;
  
  // 提取所有规格型号
  const specs = Array.from(new Set(inventorySummaryList.value.map(item => item.specification || '').filter(Boolean)));
  specificationList.value = specs;
};

// 编辑
const handleEdit = async (row: InventorySummaryItem) => {
  try {
    const response = await getInventorySummaryById(row.id);
    if ((response.code === 0 || response.code === 200) && response.data) {
      const data = response.data;
      // 复制数据到表单
      Object.assign(formData, data);
      
      // 使用materialId调用API查询物料信息
      if (data.materialId) {
        const materialResponse = await getMaterialById(data.materialId);
        if ((materialResponse.code === 0 || materialResponse.code === 200) && materialResponse.data) {
          const materialData = materialResponse.data;
          // 填充物料信息到表单
          formData.name = materialData.name;
          formData.brand = materialData.brand;
          formData.specification = materialData.specification;
        }
      }
      
      formDialogVisible.value = true;
    }
  } catch (error) {
    console.error('获取编辑数据失败:', error);
    ElMessage.error('获取数据失败');
  }
};

// 删除单个
const handleDelete = (id: number) => {
  currentDeleteId.value = id;
  confirmDialogVisible.value = true;
};

// 确认删除
const confirmDelete = async () => {
  try {
    if (currentDeleteId.value !== null) {
      // 删除单个
      await deleteInventorySummary(currentDeleteId.value);
      ElMessage.success('删除成功');
      fetchInventorySummaryList();
    }
  } catch (error) {
    console.error('删除失败:', error);
    ElMessage.error('删除失败，请稍后重试');
  } finally {
    confirmDialogVisible.value = false;
    currentDeleteId.value = null;
  }
};

// 保存
const handleSave = async () => {
  if (!formRef.value) return;
  
  try {
    await formRef.value.validate();
    
    // 更新时间
    formData.updateTime = new Date().toISOString();
    
    await updateInventorySummary(formData);
    ElMessage.success('更新成功');
    formDialogVisible.value = false;
    fetchInventorySummaryList();
  } catch (error: any) {
    console.error('保存失败:', error);
    if (error.name === 'Error') {
      ElMessage.error(error.message || '保存失败，请稍后重试');
    }
  }
};

// 搜索
const handleSearch = () => {
  pagination.currentPage = 1;
  fetchInventorySummaryList();
};

// 分页大小变化
const handleSizeChange = (size: number) => {
  pagination.pageSize = size;
  pagination.currentPage = 1;
  fetchInventorySummaryList();
};

// 当前页变化
const handleCurrentChange = (page: number) => {
  pagination.currentPage = page;
  fetchInventorySummaryList();
};

// 初始加载
onMounted(() => {
  fetchInventorySummaryList();
});
</script>

<style scoped>
/* 全局样式重置 */
* {
  box-sizing: border-box;
}

/* 主容器样式 */
.inventory-container {
  padding: 24px;
  background-color: #ffffff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  min-height: calc(100vh - 48px);
}

/* 头部操作区域 */
.header-actions {
  margin-bottom: 24px;
}

/* 搜索容器样式 */
.search-container {
  display: flex;
  align-items: center;
  gap: 16px;
  width: 100%;
  padding: 16px;
  background-color: #f8f9fa;
  border-radius: 8px;
}

.search-input-group {
  display: flex;
  gap: 16px;
  flex: 1;
  flex-wrap: wrap;
}

.search-input {
  flex: 1;
  min-width: 200px;
  border-radius: 4px;
  border: 1px solid #dcdfe6;
  transition: border-color 0.3s ease;
}

.search-input:focus-within {
  border-color: #409eff;
}

.search-button {
  white-space: nowrap;
  background-color: #409eff;
  border-color: #409eff;
  transition: all 0.3s ease;
}

.search-button:hover {
  background-color: #66b1ff;
  border-color: #66b1ff;
}

/* 表格样式优化 */
:deep(.el-table) {
  border: 1px solid #ebeef5;
  border-radius: 8px;
  overflow: hidden;
  width: 100% !important;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
}

:deep(.el-table__inner-wrapper) {
  border-radius: 8px;
  width: 100% !important;
}

:deep(.el-table th) {
  background-color: #fafafa;
  font-weight: 600;
  font-size: 14px;
  color: #303133;
  border-bottom: 1px solid #ebeef5;
  padding: 14px 16px;
  text-align: center;
}

:deep(.el-table td) {
  font-size: 14px;
  color: #606266;
  border-bottom: 1px solid #f0f0f0;
  padding: 14px 16px;
  line-height: 22px;
}

/* 表格行悬停效果 */
:deep(.el-table__row:hover > td) {
  background-color: #f5f7fa !important;
}

/* 表格斑马纹 */
:deep(.el-table__row--striped td.el-table__cell) {
  background-color: #fafafa;
}

/* 确保表格容器填满宽度 */
:deep(.el-table__header-wrapper),
:deep(.el-table__body-wrapper),
:deep(.el-table__footer-wrapper) {
  width: 100% !important;
}

/* 移除固定列相关样式 */
:deep(.el-table__fixed-right),
:deep(.el-table__fixed) {
  display: none;
}

/* 分页区域 */
.pagination-container {
  margin-top: 24px;
  display: flex;
  justify-content: flex-end;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
}

/* 对话框 */
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
}

/* 金额和数字列样式 */
:deep(.el-table-column--number .cell) {
  text-align: right;
  font-family: 'Arial', sans-serif;
}

/* 操作按钮样式 */
:deep(.el-button--link) {
  font-size: 13px;
  padding: 0 8px;
  transition: color 0.3s ease;
}

:deep(.el-button--primary.is-link) {
  color: #409eff;
}

:deep(.el-button--primary.is-link:hover) {
  color: #66b1ff;
}

:deep(.el-button--danger.is-link) {
  color: #f56c6c;
}

:deep(.el-button--danger.is-link:hover) {
  color: #f78989;
}

/* 加载状态 */
:deep(.el-loading-mask) {
  background-color: rgba(255, 255, 255, 0.8);
}

/* 响应式设计增强 */
@media (max-width: 1200px) {
  .inventory-container {
    padding: 20px;
  }
  
  .search-input-group {
    gap: 12px;
  }
  
  .search-input {
    min-width: 180px;
  }
}

@media (max-width: 1024px) {
  .search-container {
    flex-direction: column;
    align-items: stretch;
    padding: 12px;
  }
  
  .search-input-group {
    margin-bottom: 12px;
    gap: 10px;
  }
  
  .search-input {
    min-width: auto;
  }
  
  .inventory-container {
    padding: 16px;
  }
}

@media (max-width: 768px) {
  .inventory-container {
    padding: 12px;
  }
  
  .search-input-group {
    flex-direction: column;
  }
  
  :deep(.el-table th),
  :deep(.el-table td) {
    padding: 10px 8px;
    font-size: 12px;
  }
  
  .pagination-container {
    margin-top: 16px;
    padding-top: 16px;
  }
}
</style>